﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Unity.VisualScripting;
using UnityEngine;

[System.Serializable]
public class Person
{
    public char c = 'a';
    public int num = 56;
    public float fnum = 6.9f;
    public double dnum = 7.7;
    public bool isOn = true;
    public string name = "你好";
    public Item item = new Item(1, 57);
    public DTest dt = new DTest();
    public List<int> list = new List<int>() { 1,8,6,9,77};
    public List<DTest> list2 = new List<DTest>() { new DTest(), new DTest() };
    public Dictionary<int,string> dic = new Dictionary<int, string>() { { 1,"4er"},{ 2,"pl"} };   
}

[System.Serializable]
public struct Item
{
    public int id;
    public int num;

    public Item(int id, int num)
    { 
        this.id = id;
        this.num = num;
    }
}

[System.Serializable]
public class DTest
{
    public string name="ni";
}


public class BinarySerialize : MonoBehaviour
{

    void Start()
    {
        string path = Application.dataPath+"/SerializeTest.txt";
        Person person = new Person();
        person.list.Add(898);
        person.list2.Add(new DTest());
        person.dic.Add(1231312, "dsfsffsdfs");

        byte code = 123;

        // 字节流 来存储 序列化后的二进制数据
        using (MemoryStream ms = new MemoryStream())
        { 
            //实例化一个  二进制格式类  用来当转换成二进制的模板
            BinaryFormatter bf = new BinaryFormatter();

            //将转化后的二进制数据存入 流的缓冲区中
            bf.Serialize(ms, person);

            //将数据存回本地，数据在流的缓冲区中
            byte[] bytes = ms.GetBuffer();
            //对每次字节进行加密
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] ^= code;
            }

            File.WriteAllBytes(path, bytes);

            ms.Close();
        }


        //直接写入文件流中
        using (FileStream fs = File.Open(Application.dataPath + "/sstt.txt", FileMode.OpenOrCreate,
                                        FileAccess.Write))
        { 
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(fs, person);
            fs.Flush();   //清空缓冲区
            fs.Dispose();
        }


        //模拟从网络中读取字节数组并转换
        byte[] bytes2 = File.ReadAllBytes(path);

        for (int i = 0; i < bytes2.Length; i++)
        {
            bytes2[i] ^= code;
        }

        //初始化内存流
        using (MemoryStream ms = new MemoryStream(bytes2))
        {
            BinaryFormatter bf = new BinaryFormatter();
            //把 流中的二进制数据 反序列化
            Person p = bf.Deserialize(ms) as Person;

            ms.Close();
        }

        //using (FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read))
        //{ 
        //    BinaryFormatter bf = new BinaryFormatter();
        //    Person p = bf.Deserialize(fs) as Person;

        //    fs.Close();
        //}


    }

}
